package com.towexin.config.shiro;

import com.towexin.application.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * TODO
 * 验证器，增加了登录次数校验功能
 * 此类不对密码加密
 * @author Towexin
 * @version 1.0
 * @date 2021/4/21 14:32
 */

@Component
public class CustomizeLimitCredentialsMatcher extends SimpleCredentialsMatcher {
    private static final Logger log = LoggerFactory.getLogger(CustomizeLimitCredentialsMatcher.class);

    @Autowired
    private UserService userService;

    private int maxRetryNum = 5;

    public void setMaxRetryNum(int maxRetryNum) {
        this.maxRetryNum = maxRetryNum;
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = token.getPrincipal().toString();
        Integer num = userService.selectByUserName(username).getTryNum();
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            // 验证通过
            userService.changeStatus(username, Boolean.TRUE, 0);
        }else {
            if ((num+=1) >= maxRetryNum) {
                log.warn("用户[{}]进行登录验证..失败验证达到{}次", username, num);
                userService.changeStatus(username, Boolean.FALSE, 0);
                throw new LockedAccountException("userLock");
            }
            userService.changeStatus(username, Boolean.TRUE, num);
            throw new IncorrectCredentialsException("passwordError,"+(maxRetryNum-num));
        }
        return Boolean.TRUE;
    }

}
